/**
 * Description: 
 * File: uart0.c |Time: 2021-05-13 14:09
 */
#include "gpio.h"
#include "uart0.h"

void hal_uart0_init(void)
{
    // 选择引脚功能为UART
    hal_gpio_init(GPIOD, GPIO_PIN_18, ALT1);
    hal_gpio_init(GPIOD, GPIO_PIN_14, ALT1);

    // 设置通信协议
    UART0.ULCON &= ~(0x1 << 6);
    UART0.ULCON &= ~(0x1 << 5);
    UART0.ULCON &= ~(0x1 << 2);
    UART0.ULCON |= 0x3;

    // 设置波特率
    UART0.UBRDIV = 0;
    UART0.UBRDIV = 26;
    UART0.UFRACVAL = 0;
    UART0.UFRACVAL = 2;

    // 设置数据首发模式为轮训模式
    UART0.UCON &= ~(0x3 << 2);
    UART0.UCON |= 0x1 << 2;
    UART0.UCON &= ~0x3;
    UART0.UCON |= 0x1;
}

void uart_send_char(char ch)
{
    while(! (UART0.UTRSTAT & (0x1 << 1)) );
    // 发送数据
    UART0.UTXH &= ~(0xFF);
    UART0.UTXH |= ch;
}

void uart_send_string(char *str)
{
    char *tmp = str;
    while(*tmp) {
        uart_send_char(*tmp);
        tmp++;
    }

}

char uart_recv_char(void)
{
    while(! (UART0.UTRSTAT & 0x1));
    // 接收数据
    char recv = 0; 
    recv = (char)UART0.URXH;

    return recv;
}

char s[20] = {0};

char *uart_recv_string(void)
{
    char recv = 0;
    int recv_num = 0;
    do {
        recv = uart_recv_char();
        uart_send_char(recv);
        s[recv_num] = recv;
        recv_num++;

    } while(recv != '\r' && recv_num < 20);
    uart_send_char('\n');
    uart_send_char('\r');

    s[recv_num] = '\0';

    return s;
}


